﻿($ => {
    class AmisForm {
        constructor(options) {
            this.options = options;
            this.$element = this.options.$element;
            this.view = this.options.view;
            this.formData = this.options.formData;
            this.init(this.$element, this.view, this.formData);
        }
        init(ele, view, data) {
            const $ele = ele;
            if (view instanceof String) {
                view = JSON.parse(view);
            }
            this.amis = $ele.amis({
                schema: view,
                data: data,
            });
        }
        getAmisForm() {
            return this.amis.getComponentByName('form');
        }
        // 更新视图
        updateView(view, formData, context) {
            this.view = view;
            if (view instanceof String) {
                view = JSON.parse(view);
            }
            this.amis.updateSchema(view);
            this.amis.updateProps({
                data: formData, context: {
                    disabled: true,
                    ...context
                }
            });
        }
        // 设置form的值
        setData(data) {
            if (!data) {
                console.error("data is null or undefined!");
                throw new Error('data is null or undefined!');
            }
            this.data = data;
            this.getAmisForm()?.setValues({ ...data });
        }
        getData() {
            //获取整个form表单数据
            return this.getFormData();
        }
        // 获取form数据
        getFormData() {
            const values = this.getAmisForm()?.getValues() ?? {};
            return Object.keys(values).reduce((result, key) => {
                if (!key.startsWith('__')) {
                    result[key] = values[key];
                }
                return result;
            }, {});
        }
        disable() {
            this.getAmisForm()?.setValues({ disabled: true });
        }
        edit() {
            this.getAmisForm()?.setValues({ disabled: false });
        }
        doAction(actions) {
            console.log("这是doaction()方法中的this指向");
            console.log(this);
            this.amis.doAction(actions);
        }
    }

    $.fn.amisForm = function (options) {
        options ??= {};
        const registerForm = new AmisForm({ $element: this, ...options });
        return {
            updateView: registerForm.updateView.bind(registerForm),
            setData: registerForm.setData.bind(registerForm),
            getData: registerForm.getData.bind(registerForm),
            disable: registerForm.disable.bind(registerForm),
            edit: registerForm.edit.bind(registerForm),
            doAction: registerForm.doAction.bind(registerForm)
        };
    };
})(jQuery)